package com.company.beauty.common.handler;

import com.company.nuwa.common.constants.Headers;
import com.company.nuwa.common.utils.RequestContextUtil;
import com.company.nuwa.common.utils.ZkPlatformUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.math.NumberUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * <p>feign接口platformId处理</p>
 *
 * @author lili
 * @version 1.0: ZkPlatformAspect.java
 * @date 2023/11/8 10:02
 */
@Slf4j
@Component
@Aspect
public class ZkPlatformIdHandler {

    /**
     * 定义切点Pointcut
     */
    @Pointcut("execution(* com.company..facade..*(..))")
    private void facade() {
    }

    /**
     * 环绕通知
     */
    @Around(value = "facade()")
    public Object before(ProceedingJoinPoint joinPoint) throws Throwable {
        return handlePlatformId(joinPoint);
    }

    /**
     * 处理登录
     */
    private Object handlePlatformId(ProceedingJoinPoint joinPoint) throws Throwable {
        String traceId = RequestContextUtil.getHeader(Headers.TRACE_ID);
        String platformId = RequestContextUtil.getHeader(Headers.PLATFORM_ID);
        ZkPlatformUtils.setPlatformId(NumberUtils.toLong(platformId));
        log.info("[traceId: {}, platformId: {}]", traceId, platformId);
        return joinPoint.proceed();
    }

    /**
     * 移除 ThreadLocal 信息
     */
    @AfterReturning(value = "facade()")
    public void afterReturning() {
        ZkPlatformUtils.removePlatformId();
    }

}
